import 'package:flutter/material.dart';
import 'package:sharing/net/net_util.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:convert/convert.dart';
import 'package:sharing/net/ris_read_apis.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:sharing/ui/widget/user_login.dart';
import 'package:sharing/model/book_list_type.dart';

// 用户创建新的书单页面...
class CreateBookListPage extends StatefulWidget {
  CreateBookListPage({
    Key key,
  }) : super(key: key);

  _CreateBookListPageState createState() => _CreateBookListPageState();
}

class _CreateBookListPageState extends State<CreateBookListPage> {
  bool _publish = true;
  String _title = "";
  String _introduction = "";
  int _type_id = 1;
  String _activity ="科技";
  List<BookListType> _bookListTypes = [];
  List<String> _BKlistTypes =[];

  // 选择书单的类型
  ValueChanged<String> _bookListSelected (String value){
    for ( int i=0 ; i< _bookListTypes.length; i++){
      BookListType bkt = _bookListTypes[i];
      if (bkt.name == value){
        _type_id = bkt.id;
        break;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        appBar: AppBar(
          title: Text("创建新的书单"),
          elevation: 0.0,
          actions: <Widget>[
            IconButton(
              icon: Text(
                "完成",
                style: TextStyle(
                  fontSize: 16.0,
                ),
              ),
              onPressed: () {
                print("object $_introduction  $_title $_publish $_type_id");
                _createNewBookList();
              },
            )
          ],
        ),
        body: Container(
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                TextField(
                  decoration: InputDecoration(
                    prefixIcon: Container(
                      margin: const EdgeInsets.only(
                        left: 4.0,
                      ),
                      child: Text("名称"),
                    ),
                  ),
                  maxLines: 2,
                  onChanged: (str) {
                    _title = str;
                  },
                ),
                SizedBox(
                  height: 16.0,
                  child: Container(
                    color: Colors.grey[400],
                  ),
                ),
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.max,
                    children: <Widget>[
                      Container(
                        margin: const EdgeInsets.only(left: 4.0),
                        child: Text("公开"),
                      ),
                      Switch(
                        value: _publish,
                        onChanged: (bool value) {
                          print("$value");
                          setState(() {
                            _publish = !_publish;
                          });
                        },
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 16.0,
                  child: Container(
                    color: Colors.grey[400],
                  ),
                ),
                TextField(
                  decoration: InputDecoration(
                    prefixIcon: Container(
                      margin: const EdgeInsets.only(
                        left: 4.0,
                      ),
                      child: Text("简介"),
                    ),
                  ),
                  maxLines: 5,
                  onChanged: (str) {
                    _introduction = str;
                  },
                ),
                SizedBox(
                  height: 1.0,
                  child: Container(
                    height: .2,
                    color: Colors.black26,
                  ),

                ),

                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 8.0),
                  width: double.infinity,
                  child: InputDecorator(
                    decoration: const InputDecoration(
                      labelText: '请选择书单的类型',
                      hintText: 'Choose an activity',
                      contentPadding: EdgeInsets.zero,
                    ),
                    isEmpty: _activity == null,
                    child: DropdownButton<String>(
                      value: _activity,
                      onChanged: (String newValue) {
                        setState(() {
                          _activity = newValue;
                          _bookListSelected(newValue);
                        });
                      },
                      items: _generateBookListTypesWidgets(),
                    ),
                  ),
                )
              ],
            ),
          ),
        ),
      ),
    );
  }

  List <DropdownMenuItem> _generateBookListTypesWidgets(){

    _BKlistTypes = _bookListTypes.map((BookListType bkt){
      return bkt.name;
    }).toList();
  print("create _generateBookListTypesWidget $_BKlistTypes");

  return   _BKlistTypes.map<DropdownMenuItem<String>>((String value) {
      return DropdownMenuItem<String>(
        value: value,
        child: Text(value),
      );
    }).toList();

  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fetchBookListTypes();
  }

  // 获取书单的类型
  void _fetchBookListTypes() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    await NetUtil.originGet(
        WholeApis.hostName + RisReadApis.bookListTypes,
        Options(
          headers: {"authorization": authorization},
        ), (Response response) {
      print("_fetchBookListTypes response > ${response.data}");
      var code = response.data["code"];
      // 返回的状态为200 和 message 属性不为null
      if (code == 200 && response.data["message"] != null) {
        print("解包书单类型");
        _bookListTypes = BookListType.fromJson(response.data["message"]);
        setState(() {
          // do something
        });
      } else {
        // todo 用户没有登录
        prefs.remove("authorization");
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) {
            return Login();
          }),
        );
      }
    });
  }

// 创建书单...
  void _createNewBookList() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    print("$authorization");
    //await prefs.setString('authorization', auth);
    await NetUtil.createNewBookList(
      (Response response) {
        if (response.statusCode != 200) {
          return;
        }

        print("data > response.statusCode ${response.statusCode}");

        // 创建书单成功... 跳出页面
        Navigator.pop(context);
      },
      Options(
        headers: {
          "authorization": authorization,
          "content-Type":"application/json",
        },
        data: {
          "name": _title,
          "publish": _publish,
          "instruction": _introduction,
          "type_id":_type_id
        },

      ),
    );
  }
}
